package algorithm;

public class AsyncPrintNumber {
    private static int number = 0;
    private static final Object object = new Object();

    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (number < 100) {
                    // 请求锁,阻塞
                    synchronized (object) {
                        if (number % 2 == 1) {
                            System.out.println("Thread1: " + number++);
                        }
                    }
                }
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (number < 100) {
                    // 请求锁
                    synchronized (object) {
                        if (number % 2 == 0) {
                            System.out.println("Thread2: " + number++);
                        }
                    }
                }
            }
        });

        thread1.start();
        thread2.start();
    }
}
